package com.rsy.crm.workbench.web.controller;

import com.rsy.crm.settings.domain.User;
import com.rsy.crm.settings.service.Impl.UserServiceImpl;
import com.rsy.crm.settings.service.UserService;
import com.rsy.crm.util.DateTimeUtil;
import com.rsy.crm.util.PrintJson;
import com.rsy.crm.util.ServiceFactory;
import com.rsy.crm.util.UUIDUtil;
import com.rsy.crm.workbench.domain.Customer;
import com.rsy.crm.workbench.domain.Tran;
import com.rsy.crm.workbench.domain.TranHistory;
import com.rsy.crm.workbench.service.CustomerService;
import com.rsy.crm.workbench.service.Impl.CustomerServiceImpl;
import com.rsy.crm.workbench.service.Impl.TranServiceImpl;
import com.rsy.crm.workbench.service.TranService;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交易模块
 */
public class TransactionController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("进入到交易控制器");

        String path = request.getServletPath();

        if("/workbench/transaction/add.do".equals(path)){
            addBtn(request,response);

        }else if("/workbench/transaction/getCustomerName.do".equals(path)){
            getCustomerName(request,response);
        } if ("/workbench/transaction/save.do".equals(path)){
            save(request,response);
        }else if ("/workbench/transaction/getTranList.do".equals(path)){
            getTranList(request,response);
        }else if ("/workbench/transaction/detail.do".equals(path)){
            detail(request,response);
        }else if ("/workbench/transaction/getTranHistoryByTranId.do".equals(path)){
            getTranHistoryByTranId(request,response);
        }else if("/workbench/transaction/changeStage.do".equals(path)){
            changeStage(request,response);
        }else if ("/workbench/transaction/getCharts.do".equals(path)){
            getCharts(request,response);
        }

    }

    /**
     * 交易阶段漏斗图
     * @param request
     * @param response
     */
    private void getCharts(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("交易阶段漏斗图");
        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());

        Map<String,Object> map = ts.getCharts();

        PrintJson.printJsonObj(response,map);
    }

    /**
     * 改变交易阶段
     * @param request
     * @param response
     */
    private void changeStage(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("执行改变阶段的操作");
        String id = request.getParameter("id");
        String stage = request.getParameter("stage");
        String money = request.getParameter("money");
        String expectedDate = request.getParameter("expectedDate");
        String editTime = DateTimeUtil.getSysTime();
        String editBy = ((User)request.getSession().getAttribute("user")).getName();
        Tran tran = new Tran();
        tran.setId(id);
        tran.setStage(stage);
        tran.setMoney(money);
        tran.setExpectedDate(expectedDate);
        tran.setEditTime(editTime);
        tran.setEditBy(editBy);

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        boolean flag = ts.changeStage(tran);
        //取可能性
        Map<String,String> pMap = (Map<String, String>) request.getServletContext().getAttribute("pMap");
        tran.setPossibility(pMap.get(stage));

        Map<String,Object> map = new HashMap<>();
        map.put("success",flag);
        map.put("tran",tran);
        PrintJson.printJsonObj(response,map);
    }

    /**
     * 详细信息页的历史交易
     * @param request
     * @param
     */
    private void getTranHistoryByTranId(HttpServletRequest request,HttpServletResponse response) {

        System.out.println("历史交易");
        String tranId = request.getParameter("tranId");

        TranService tranService = (TranService) ServiceFactory.getService(new TranServiceImpl());

        List<TranHistory> list = tranService.getTranHistoryByTranId(tranId);
        Map<String,String> map = (Map<String,String>) request.getServletContext().getAttribute("pMap");

        for(TranHistory th:list){
            String stage = th.getStage();
            String possibiltiy = map.get(stage);
            th.setPossibility(possibiltiy);
        }

        PrintJson.printJsonObj(response,list);

    }

    /**
     * 详细信息页
     * @param request
     * @param response
     */
    private void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入交易-跳转详细页-查询相关信息操作");
        String id = request.getParameter("id");
        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        Tran t = ts.getTranById(id);

        String stage = t.getStage();
        Map<String,String> pMap = (Map<String, String>) request.getServletContext().getAttribute("pMap");
        String possibility = pMap.get(stage);
        t.setPossibility(possibility);

        request.setAttribute("t",t);
        request.getRequestDispatcher("/workbench/transaction/detail.jsp").forward(request,response);
    }

    private void getTranList(HttpServletRequest request, HttpServletResponse response) {

    }

    /**
     * 添加线索
     * @param request
     * @param response
     */
    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("执行添加交易操作");
        String id = UUIDUtil.getUUID();
        String owner = request.getParameter("owner");
        String money = request.getParameter("money");
        String name = request.getParameter("name");
        String expectedDate = request.getParameter("expectedDate");
        String customerName = request.getParameter("customerName");
        String stage = request.getParameter("stage");
        String type = request.getParameter("type");
        String source = request.getParameter("source");
        String activityId = request.getParameter("activityId");
        String contactsId = request.getParameter("contactsId");
        String createBy = ((User)request.getSession().getAttribute("user")).getName();
        String createTime = DateTimeUtil.getSysTime();
        String description = request.getParameter("description");
        String contactSummary = request.getParameter("contactSummary");
        String nextContactTime = request.getParameter("nextContactTime");

        Tran t = new Tran();
        t.setId(id);
        t.setOwner(owner);
        t.setMoney(money);
        t.setName(name);
        t.setExpectedDate(expectedDate);
        t.setCustomerId(customerName);
        t.setStage(stage);
        t.setType(type);
        t.setSource(source);
        t.setActivityId(activityId);
        t.setContactsId(contactsId);
        t.setCreateBy(createBy);
        t.setCreateTime(createTime);
        t.setDescription(description);
        t.setContactSummary(contactSummary);
        t.setNextContactTime(nextContactTime);

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        boolean flag = ts.save(t,customerName);
        if (flag){
            //转发（一般用于session存值的时候）
            //重定向
            response.sendRedirect(request.getContextPath()+"/workbench/transaction/index.jsp");
        }
    }

    /**
     * 获取客户名字
     * @param request
     * @param response
     */
    private void getCustomerName(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("取得 客户名称列表（按照客户名称进行模糊查询）");

        String name = request.getParameter("name");

        CustomerService cs = (CustomerService) ServiceFactory.getService(new CustomerServiceImpl());

        List<String> sList = cs.getCustomerName(name);

        PrintJson.printJsonObj(response,sList);

    }

    /**
     * 添加页面所有者
     * @param request
     * @param response
     */
    private void addBtn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入到跳转到交易添加页的操作");

        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());

        List<User> uList = us.getUserList();

        request.setAttribute("uList", uList);
        request.getRequestDispatcher("/workbench/transaction/save.jsp").forward(request, response);

    }
}
